package gcode.helloworld.java.socket.linecaller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

public class Client {
	public static void main(String args[]){
		org.apache.log4j.BasicConfigurator.configure();
		Client c=new Client();
		try {
			c.contect("127.0.0.1", 9005);
			String msg=c.call("hello world!");
			System.out.println("REC:"+msg);
			c.call("abc\nbcd\n");
			System.out.println("REC:"+msg);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			c.close();
		}
		System.out.println("END!");
	}
	private Logger log=null;
	private String serverIp	= null;
	private int serverPort	= 0;

	private Socket socket	= null;
	private BufferedReader in	= null;
	private PrintWriter out		= null;
	private InetAddress localAddress;
	private int localPort;
	
	public Client(){
		log=Logger.getLogger(this.getClass());
		setServerIp("127.0.0.1");
		setServerPort(9005);
	}
	public void contect(String serverIp,int serverPort) throws UnknownHostException, IOException{
		log.info("contect "+serverIp+" "+serverPort);
		this.setServerIp(serverIp);
		this.setServerPort(serverPort);
		socket = new Socket(serverIp, serverPort);
		localAddress=socket.getLocalAddress();
		localPort=socket.getLocalPort();
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		out = new PrintWriter(socket.getOutputStream());
	}
	public void close(){
		if(out!=null){
			out.println("<CLOSE "+localAddress+":"+localPort+"/>");
			out.close(); 
		}
		try { if(in!=null){in.close();} } catch (IOException e) { log.error("run Exception "+e.getMessage(),e);}
		try { socket.close(); } catch (IOException e) { log.error("run Exception "+e.getMessage(),e);}
	}
	public String call(String msg) throws IOException{
		if(out==null||in==null){
			return null;
		}
		String ls[]=msg.split("\n");
		if(ls.length==1){
			out.println(msg);
			out.flush();
		}else{
			out.println("<DATA "+localAddress+":"+localPort+">");
			for(int i=0;i<ls.length;i++){
				out.println(ls[i]);
				if(i%100==0){
					out.flush();
				}
			}
			out.println("</DATA "+localAddress+":"+localPort+">");
			out.flush();
		}
		String data=in.readLine();
		return data;
	}
	private void setServerIp(String serverIp) {
		this.serverIp = serverIp;
	}
	private void setServerPort(int serverPort) {
		this.serverPort = serverPort;
	}
	public String getServerIp() {
		return serverIp;
	}
	public int getServerPort() {
		return serverPort;
	}
}
